﻿using FireAlarmService.TunnelUI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FireAlarmService
{
    public partial class FireAlarmForm : Form
    {

        //public string tempinfo = "\r\n手报  ::  11:12:31 05/04/2018 控制盘:01  卡:03  器件:0129\r\n灌林岩山隧道 手报07号\r\n";
        public FireAlarmForm()
        {
            InitializeComponent();
        }
        DataConnectionServicesClient uiService = new DataConnectionServicesClient();
        DataTable fireAlarmTable = new DataTable();
        SerialPort serialPort = new SerialPort();

        private void SendMessageToUI(string alarmString)
        {
            string deviceId;
            string deviceType;
            FireAlarmInfo fireAlarmInfo = new FireAlarmInfo(alarmString);
            try
            {
                DataRow deviceInfo = fireAlarmTable.Select($"ControlPanel='{fireAlarmInfo.ControlPanel}' and Card='{fireAlarmInfo.Card}' and Device='{fireAlarmInfo.Device}'")[0];
                deviceId = deviceInfo["DeviceID"].ToString();
                deviceType = deviceInfo["TypeID"].ToString();
            }
            catch
            {
                deviceId = string.Empty;
                deviceType = string.Empty;
            }

            if ((!string.IsNullOrEmpty(deviceId)) && (!string.IsNullOrEmpty(deviceType)))
            {
                switch (deviceType)
                {
                    case "FD":
                        {
                            switch (fireAlarmInfo.AlarmType)
                            {
                                case "手报":
                                    {
                                        try
                                        {
                                            uiService.ChangeDeviceStatusAsync(deviceId, "041", fireAlarmInfo.AlarmType, deviceType, fireAlarmInfo.AlarmTime.ToString());
                                            ChangeDbDeviceStatus(deviceId, "041", fireAlarmInfo.AlarmType);
                                            InsertDbAlarm(deviceId, fireAlarmInfo.AlarmTime, fireAlarmInfo.AlarmType);
                                        }
                                        catch { }
                                    }
                                    break;
                                case "恢复":
                                    {
                                        try
                                        {
                                            uiService.ChangeDeviceStatusAsync(deviceId, "040", "正常", deviceType, fireAlarmInfo.AlarmTime.ToString());
                                            ChangeDbDeviceStatus(deviceId, "040", "正常");
                                        }
                                        catch { }
                                    }
                                    break;
                                case "故障":
                                    {
                                        try
                                        {
                                            uiService.ChangeDeviceStatusAsync(deviceId, "042", fireAlarmInfo.AlarmType, deviceType, fireAlarmInfo.AlarmTime.ToString());
                                            ChangeDbDeviceStatus(deviceId, "042", fireAlarmInfo.AlarmType);
                                            InsertDbAlarm(deviceId, fireAlarmInfo.AlarmTime, fireAlarmInfo.AlarmType);
                                        }
                                        catch { }
                                    }
                                    break;
                            }
                        }
                        break;
                    case "Smoke":
                        {
                            switch (fireAlarmInfo.AlarmType)
                            {
                                case "火警":
                                    {
                                        try
                                        {
                                            uiService.ChangeDeviceStatusAsync(deviceId, "045", fireAlarmInfo.AlarmType, deviceType, fireAlarmInfo.AlarmTime.ToString());
                                            ChangeDbDeviceStatus(deviceId, "045", fireAlarmInfo.AlarmType);
                                            InsertDbAlarm(deviceId, fireAlarmInfo.AlarmTime, fireAlarmInfo.AlarmType);
                                        }
                                        catch { }
                                    }
                                    break;
                                case "恢复":
                                    {
                                        try
                                        {
                                            uiService.ChangeDeviceStatusAsync(deviceId, "046", "正常", deviceType, fireAlarmInfo.AlarmTime.ToString());
                                            ChangeDbDeviceStatus(deviceId, "046", "正常");
                                        }
                                        catch { }
                                    }
                                    break;
                                case "故障":
                                    {
                                        try
                                        {
                                            uiService.ChangeDeviceStatusAsync(deviceId, "047", fireAlarmInfo.AlarmType, deviceType, fireAlarmInfo.AlarmTime.ToString());
                                            ChangeDbDeviceStatus(deviceId, "047", fireAlarmInfo.AlarmType);
                                            InsertDbAlarm(deviceId, fireAlarmInfo.AlarmTime, fireAlarmInfo.AlarmType);
                                        }
                                        catch { }
                                    }
                                    break;
                            }
                        }
                        break;
                    case "Fiber":
                        {
                            switch (fireAlarmInfo.AlarmType)
                            {
                                case "与组":
                                    {
                                        try
                                        {
                                            uiService.ChangeDeviceStatusAsync(deviceId, "048", "高温", deviceType, fireAlarmInfo.AlarmTime.ToString());
                                            ChangeDbDeviceStatus(deviceId, "048", "高温");
                                            InsertDbAlarm(deviceId, fireAlarmInfo.AlarmTime, fireAlarmInfo.AlarmType);
                                        }
                                        catch { }

                                    }
                                    break;
                                case "恢复":
                                    {
                                        try
                                        {
                                            uiService.ChangeDeviceStatusAsync(deviceId, "049", "正常", deviceType, fireAlarmInfo.AlarmTime.ToString());
                                            ChangeDbDeviceStatus(deviceId, "049", "正常");
                                        }
                                        catch { }

                                    }
                                    break;
                                case "故障":
                                    {
                                        try
                                        {
                                            uiService.ChangeDeviceStatusAsync(deviceId, "050", fireAlarmInfo.AlarmType, deviceType, fireAlarmInfo.AlarmTime.ToString());
                                            ChangeDbDeviceStatus(deviceId, "050", fireAlarmInfo.AlarmType);
                                            InsertDbAlarm(deviceId, fireAlarmInfo.AlarmTime, fireAlarmInfo.AlarmType);
                                        }
                                        catch { }

                                    }
                                    break;
                            }
                        }
                        break;
                    default: break;
                }
                tbHistory.BeginInvoke(new Action(() => {
                    tbHistory.Text += deviceId + "  " + (new FireAlarmInfo(alarmString).ToString()) + "\r\n";
                    lastAlarmInfo.Text = deviceId + "  " + (new FireAlarmInfo(alarmString).ToString());
                }));
            }
        }

        /// <summary>
        /// 修改数据库中状态表
        /// </summary>
        /// <param name="deviceId">设备ID</param>
        /// <param name="statusId">状态ID</param>
        /// <param name="statusDescription">状态描述</param>
        private void ChangeDbDeviceStatus(string deviceId, string statusId, string statusDescription)
        {
            DBHelper sdh = new DBHelper();
            string updatesql = "update M_Device set DeviceStatusID='" + statusId + "',UpdateTime='" + DateTime.Now.ToString() + "' where DeviceID='" + deviceId + "'";
            sdh.RunCommandAsync(updatesql);
        }
        /// <summary>
        /// 增加报警信息
        /// </summary>
        /// <param name="deviceId">设备ID</param>
        /// <param name="alarmTime">报警时间</param>
        /// <param name="alarmInfo">报警内容</param>
        private void InsertDbAlarm(string deviceId, DateTime alarmTime, string alarmInfo)
        {
            DBHelper sdh = new DBHelper();
            string updatesql = "insert into H_AlarmInfo(AlarmID,DeviceID,AlarmTime,AlarmInfo) values ('" + DBHelper.GetGuid + "','" + deviceId + "','" + alarmTime.ToString() + "','" + alarmInfo + "')";
            sdh.RunCommandAsync(updatesql);
        }

        private async void FireAlarmForm_Load(object sender, EventArgs e)
        {
            DBHelper dh = new DBHelper();
            fireAlarmTable = await dh.GetTableAsync("SELECT  R_FireAlarmDevice.ControlPanel, R_FireAlarmDevice.Card, R_FireAlarmDevice.Device, R_FireAlarmDevice.AlarmType, R_FireAlarmDevice.AlarmTime, R_FireAlarmDevice.DeviceID, M_Device.DeviceID AS Expr1, M_Device.DeviceStatusID, M_Device.TypeID FROM R_FireAlarmDevice INNER JOIN M_Device ON R_FireAlarmDevice.DeviceID = M_Device.DeviceID");
            serialPort.PortName = Properties.Settings.Default.PortName;
            serialPort.BaudRate = Properties.Settings.Default.BaudRate;
            serialPort.DataBits = Properties.Settings.Default.DataBits;

            serialPort.DataReceived += SerialPort_DataReceived;
            try
            {
                serialPort.Open();
                串口.Text = $"{serialPort.PortName}已打开";
            }
            catch
            {
                MessageBox.Show("串口打开失败");
            }
        }

        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Task.Delay(200).Wait();
            byte[] reDatas = new byte[serialPort.BytesToRead];
            serialPort.Read(reDatas, 0, reDatas.Length);
            string alarmString = Encoding.Default.GetString(reDatas);
            SendMessageToUI(alarmString);
        }        

        private void resetFireAlarmInfo_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("本功能可以手动恢复火灾报警信息\r\n报警主机恢复时如果与本机断开联系，方可使用本功能。\r\n您确定要恢复火灾报警信息吗？", "确认恢复火灾报警设备信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
            if (dr == DialogResult.OK)
            {
                string deviceId;
                string deviceType;
                foreach (DataRow dataRow in fireAlarmTable.Rows)
                {
                    deviceId = dataRow["DeviceID"].ToString();
                    deviceType = dataRow["TypeID"].ToString();

                    switch (deviceType)
                    {
                        case "FD":
                            {
                                try
                                {
                                    uiService.ChangeDeviceStatusAsync(deviceId, "040", "正常", deviceType, DateTime.Now.ToString());
                                    ChangeDbDeviceStatus(deviceId, "040", "正常");
                                }
                                catch { }
                            }
                            break;
                        case "Smoke":
                            {
                                try
                                {
                                    uiService.ChangeDeviceStatusAsync(deviceId, "046", "正常", deviceType, DateTime.Now.ToString());
                                    ChangeDbDeviceStatus(deviceId, "046", "正常");
                                }
                                catch { }
                            }
                            break;
                        case "Fiber":
                            {
                                try
                                {
                                    uiService.ChangeDeviceStatusAsync(deviceId, "049", "正常", deviceType, DateTime.Now.ToString());
                                    ChangeDbDeviceStatus(deviceId, "049", "正常");
                                }
                                catch { }
                            }
                            break;
                        default: break;
                    }
                }
            }
        }

        private void tbHistory_TextChanged(object sender, EventArgs e)
        {
            if(tbHistory.Lines.Count()>200)
            {
                tbHistory.Text = string.Empty;
            }
        }
    }
}
